<template>
	<view class="container">
		<!-- 颈部查询 -->
		<view class="navbar">
			<view class="search-item" v-for="(item,index) in formList">
				<view class="label">
					{{ item.label}}
				</view>
				<u-input v-model="form[item.prop]" :placeholder="item.placeholder||'请输入'" border></u-input>
			</view>
			<view class="button-part">
				<u-button type="primary" size="mini" @click="dataSearch">查询</u-button>
			</view>

		</view>
		<!-- 数据表格 -->
		<view class="content">
			<view class="table-head">
				<u-table>
					<u-tr>
						<u-th v-for="(col,colIndex) in tableDatas.columns" :key="colIndex" :width="col.width">
							{{col.label}}
						</u-th>
					</u-tr>
				</u-table>
			</view>
			<view class="table-body">
				<scroll-view scroll-y="true" style="height: 100%;" @scrolltolower="scrolltolower()"
					:lower-threshold="3">
					<u-table font-size="24">
						<u-tr v-for="(row,rowIndex) in tableDatas.datas" :key="rowIndex">
							<u-td v-for="(col,colIndex) in tableDatas.columns" :key="colIndex" :width="col.width"
								:class="`col-${colIndex} ${col.prop==='edit'?'col-edit':''}`"
								@click.native="clickRow(row,col)">
								{{ col.prop==='edit'? (row['FileName'] ?'查看图纸':''): row[col.prop]}}
							</u-td>
						</u-tr>
						<u-loadmore :status="tableDatas.loadmoreVisible" @loadmore="loadMore()" color="#3e82f9" />
					</u-table>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import myTab from '@/components/myTabs/index.vue'
	export default {
		components: {
			myTab
		},
		data() {
			return {
				formList: [{
						label: '图号：',
						prop: 'Code',
						placeholder: '请输入'
					},
					{
						label: '品名：',
						prop: 'MaterialName',
						placeholder: '请输入'
					}
				],
				form: {
					page: 1,
					rows: 50,
				},
				tableDatas: {
					dicID: 1180,
					datas: [],
					columns: [{
							prop: 'Code',
							label: '图号',
							width: '35%'
						},
						{
							prop: 'MaterialName',
							label: '品名',
							width: '45%'
						},
						{
							prop: 'edit',
							label: '操作',
							width: '20%',
						},
					],
					formData: {},
					loading: false,
					loadmoreVisible: 'loadmore',
					loadText: '滚动或点击加载更多',
					count: 0,
					selectAll: false
				},
				permission: false,
				// 查看pdf
				currentFile: null, // 当前打开的文件信息
				fileQueue: [] // 文件队列，用于处理连续打开
			}
		},
		onLoad() {
			this.permission = this.$store.getters.userInfo.RoleMap?.some(val => val.RoleID === 'E01Admin' || val
				.RoleID ===
				'RR202506040001') // 管理员和查看图纸角色
			this.formList.forEach(val => {
				this.$set(this.form, val.prop, val.value || null)
			})
			this.getApsData()
		},
		methods: {
			formatDate(val, format = 'yyyy-mm-dd') {
				return this.$u.timeFormat(new Date(val), format)
			},
			dataSearch() {
				this.form.page = 1
				this.getApsData()
			},
			// 获取数据
			async getApsData(remark = 0) {
				const condition = {
					dicID: this.tableDatas.dicID,
				}
				Object.assign(condition, this.form)
				this.tableDatas.loading = true
				if (this.form.page === 1) {
					this.tableDatas.datas.length = 0
				}
				this.setLoadmore('loading')
				const res = await this.$request.post({
					url: '/APSAPI/APSData',
					data: condition
				}).catch(err => err)
				this.tableDatas.loading = false
				if (!res) return
				const {
					result,
					msg,
					data,
					count
				} = res
				if (!result) return uni.showToast({
					title: msg,
					icon: 'error'
				})
				if (res.result) {
					this.$set(this.tableDatas, 'count', count)
					if (!res.data.length) {
						this.setLoadmore('nomore')
					} else {
						this.tableDatas.datas.push(...res.data)
						this.setLoadmore('loadmore')
					}
				} else {
					return Promise.reject()
				}
			},
			// 加载更多
			loadMore() {
				if (this.tableDatas.loadmoreVisible === 'nomore') return
				this.form.page++
				this.getApsData()
			},
			//配置加载更多
			setLoadmore(status = 'loadmore') {
				const textMenu = {
					loadmore: '滑动或点击加载更多',
					loading: '加载中...',
					nomore: '已无更多数据',
				}
				this.$set(this.tableDatas, 'loadmoreVisible', status)
				this.$set(this.tableDatas, 'loadmoreText', textMenu[status])
			},
			// 表格滚动到底部
			scrolltolower() {
				this.loadMore()
			},
			clickRow(row, col) {
				if (!this.permission) return uni.showToast({
					title: '无权限',
					icon: 'error'
				})
				const fileName = row['FileName'];
				if (!fileName) return
				const baseUrl = uni.getStorageSync('url') || '';
				const token = uni.getStorageSync('token')
				const pdfUrl = baseUrl + '/APSAPI/ViewPDF?ID=' + row.MaterialID + '&CrurentAccount=' + token + '&down=1'
				this.openPdf(pdfUrl, fileName)
			},
			/**
			 * 打开PDF文件
			 * @param {String} pdfUrl PDF文件URL
			 * @param {String} [fileName] 自定义文件名（不带后缀）
			 */
			async openPdf(pdfUrl, fileName) {
				// 加入队列，防止重复点击
				if (this.fileQueue.includes(pdfUrl)) return;
				this.fileQueue.push(pdfUrl);

				try {
					// 先关闭已打开的文件（如果有）
					await this.cleanCurrentFile();

					// 下载文件
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					const filePath = await this.downloadPdf(pdfUrl, fileName);

					// 保存当前文件信息
					this.currentFile = {
						url: pdfUrl,
						path: filePath,
						timestamp: Date.now()
					};

					// 打开文档
					await this.openDocument(filePath);

				} catch (error) {
					console.error('打开PDF失败:', error);
					uni.showToast({
						title: '打开文件失败',
						icon: 'none'
					});
				} finally {
					// 从队列中移除
					this.fileQueue = this.fileQueue.filter(url => url !== pdfUrl);
					uni.hideLoading();
				}
			},

			/**
			 * 下载PDF文件
			 */
			downloadPdf(url, fileName) {
				return new Promise((resolve, reject) => {
					// 生成固定名称的文件路径
					const filePath = `${this.getDocumentDir()}/${fileName || 'temp_pdf.pdf'}`;
					console.log('filePath', filePath)
					uni.downloadFile({
						url: url,
						filePath: filePath, // 指定固定路径，避免数字后缀
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res.filePath || res.tempFilePath);
							} else {
								reject(new Error(`下载失败，状态码: ${res.statusCode}`));
							}
						},
						fail: reject
					});
				});
			},

			/**
			 * 打开文档
			 */
			openDocument(filePath) {
				console.log('openDocument', filePath)
				return new Promise((resolve, reject) => {
					uni.openDocument({
						filePath: filePath,
						fileType: 'pdf',
						success: resolve,
						fail: reject
					});
				});
			},

			/**
			 * 清理当前文件
			 */
			async cleanCurrentFile() {
				if (!this.currentFile?.path) return;

				try {
					await this.removeFile(this.currentFile.path);
					console.log('已清理临时文件:', this.currentFile.path);
				} catch (error) {
					console.error('清理文件失败:', error);
				} finally {
					this.currentFile = null;
				}
			},

			/**
			 * 删除文件
			 */
			removeFile(filePath) {
				return new Promise((resolve) => {
					uni.removeSavedFile({
						filePath: filePath,
						complete: resolve
					});
				});
			},

			/**
			 * 获取应用文档目录
			 */
			getDocumentDir() {
				// 优先使用5+ API
				// if (window.plus && plus.io) {
				// 	return plus.io.PUBLIC_DOCUMENTS;
				// }

				// uni-app官方API
				if (uni.env && uni.env.USER_DATA_PATH) {
					return uni.env.USER_DATA_PATH;
				}

				// 默认路径
				return 'file:///storage/emulated/0/Download/';
			}

		},
		// 页面生命周期 - 处理返回键等场景
		onHide() {
			// this.cleanCurrentFile();
		},

		onUnload() {
			this.cleanCurrentFile();
		}
	}
</script>

<style scoped lang="scss">
	* {
		box-sizing: border-box;
	}

	.container {
		width: 100%;
		height: 100vh;
		overflow: hidden;

		.header {
			height: 81rpx;
			// border-bottom: 1px solid $uni-border-color;
		}

		.navbar {
			padding: 0 10rpx;
			height: 80rpx;
			display: flex;
			flex-wrap: nowrap;

			.search-item {
				flex-grow: 1;
				padding-right: 20rpx;
				display: flex;
				flex-wrap: nowrap;
				align-items: center;
			}

			.button-part {
				width: 150rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.content {
			height: calc(100vh - 80rpx);
			width: 100%;
			// flex: 1;
			display: flex;
			flex-direction: column;
			padding: 10rpx 10rpx 20rpx;
			overflow: hidden;

			.table-head {}

			.table-body {
				flex-grow: 1;
				width: 100%;
				overflow: hidden;

				uni-scroll-view {
					height: 100%;
				}

				.u-table {
					width: 100%;
					overflow-y: auto;
					overflow-x: hidden;
				}
			}

			.u-td,
			.u-th {
				white-space: nowrap !important;
				overflow: hidden !important;
				text-overflow: ellipsis !important;
				min-width: 0 !important;
				/* 关键属性 */
				flex-shrink: 0 !important;
				/* 防止flex容器压缩 */
			}

			.u-td {
				height: auto !important;
			}

			.col-1 {
				white-space: pre-wrap !important;
			}

			.col-0 {
				// font-size: 18rpx !important;
				white-space: pre-wrap !important;
				font-weight: bold;
			}

			.col-2 {
				color: $uni-color-primary !important;
				text-decoration-line: underline;
			}

		}

		.footer {
			height: 60rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			padding-right: 20rpx;
		}
	}
</style>